import { Component } from "react";

import './Article.css';

import ArticleItem from './ArticleItem';

import bus from './EventBus';

// 定义有状态组件
class ArticleList extends Component {
    constructor(props){
        super(props);
        this.state = {
            articles: [
                { id: 1234 , title: '春晓' , author: '孟浩然' },
                { id: 2345 , title: '将进酒' , author: '李白' },
                { id: 2233 , title: '滕王阁序' , author: '王勃' },
                { id: 3344 , title: '咏鹅' , author: '骆宾王' }
            ]
        }
    }
    render(){
        const articles = this.state.articles ;
        return (
            <div className="article-list">
                { articles.map( this.mapper ) }
            </div>
        )
    }
    mapper( article , index ){
        return (<ArticleItem ordinal={index+1} article={article} key={article.id}></ArticleItem>)
    }
    componentDidMount(){
        // 启用事件监听
        bus.on( '展示详情' , id => console.log( `准备显示的${id}详情`) );

        bus.on( '删除文章' , id => {
            let articles = this.state.articles;
            let index = articles.findIndex( a => a.id === id );
            if( index != -1 ) {
                articles.splice( index , 1 );
                this.setState( { articles: articles } )
            }
        });
    }
}

export default ArticleList ;